package org.ainlolcat.ainscience.utils.executor;

import org.ainlolcat.Variable;
import org.ainlolcat.aincalc2.Leksemma;
import org.ainlolcat.aincalc2.MissingDependenciesException;
import org.ainlolcat.ainscience.column.Column;
import org.ainlolcat.ainscience.entity.Entity;

/**
 * @author ainlolcat
 *         Date: 11/4/13
 */
public class FunctionExecutor {
    Entity entity;
    int row = 0;

    public FunctionExecutor() {
    }

    public FunctionExecutor(Entity entity) {
        this.entity = entity;
    }

    public Variable perform(String name, Variable... args){
        if ("sin".equals(name))
            return new Variable(Math.sin(args[0].getDoubleValue()));
        if ("val".equals(name))
            return getVariableThroughLink(args[0], args[1]);
        return null;
    }

    public void setRow(int newrow){
        row = newrow;
    }

    private Variable getVariableThroughLink(Variable a,Variable b){
        if (b!= null){
            String linkname = a.getStringValue();
            return entity.getLink(linkname).getValue(
                    b.getIntegerValue(),     //columnID
                    row
            );
        }
        else{
            Column column = null;
            if (a.getType() == Variable.TYPE_STRING){
                column = entity.getColumnByName(a.getStringValue());
            } else {
                column = entity.getColumnByOrder(a.getIntegerValue());
            }
            if (column == null)
                throw new MissingDependenciesException(entity.getName(), a.getStringValue());
            return column.getCanonicalValue(row);
        }
    }
}
